﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace LastFmUriHandler
{
    public partial class Form1 : Form
    {

        protected const string _regKey = "Software\\Grondwerk.it\\LastFmUriHandler";

        protected Slim _slim;
        protected string[] _players;
        protected Timer _timer = new Timer();

        public Form1(string[] pars)
        {
            InitializeComponent();

            // refresh players
            RefreshPlayers();

            // timer 
            _timer.Tick += new EventHandler(_timer_Tick);

            // URI parameter?
            if (pars.Length > 0)
            {
                LastFmUri.Text = pars[0];
                PlayUri();
            }
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            if (AutoClose.Checked)
                Application.Exit();
        }

        private void LastFmUri_TextChanged(object sender, EventArgs e)
        {
            PlayUri();
        }

        private void RegisterHandler()
        {

            // HKEY_CLASSES_ROOT
            //     alert
            //          URL Protocol = ""
            // Under this new key, the URL Protocol string value indicates that this key declares a custom protocol handler. Without this key, the handler application will not launch. The value should be an empty string.

            // Keys should also be added for DefaultIcon and shell. The Default string value of the DefaultIcon key must be the file name to use as an icon for this new URL protocol. The string takes the form "path, iconindex" with a maximum length of MAX_PATH. The name of the first key under the shell key should be an action verb, such as open. Under this key, a command key or a DDEEXEC key indicate how the handler should be invoked. The values under the command and DDEEXEC keys describe how to launch the application handling the new protocol.

            // Finally, the Default string value should contain the display name of the new protocol. The following example shows how to register an application, alert.exe in this case, to handle the alert protocol.

            // HKEY_CLASSES_ROOT
            //     alert
            //          (Default) = "URL:Alert Protocol"
            //          URL Protocol = ""
            //          DefaultIcon
            //               (Default) = "alert.exe,1"
            //          shell
            //               open
            //                    command
            //                         (Default) = "C:\Program Files\Alert\alert.exe" "%1"

            //string protocol = "lastfm";
            //string program = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;

            //RegistryKey key = Registry.ClassesRoot.CreateSubKey(protocol);
            //key.SetValue("URL Protocol", "");


        }

        private void button2_Click(object sender, EventArgs e)
        {
            PlayUri();
        }

        private void PlayUri()
        {
            if (_players == null)
                return;

            string uri = LastFmUri.Text;
            _slim = new Slim(SqueezeCenterUrl.Text);
            _slim.PlayUri(_players[PlayersCombo.SelectedIndex], LastFmUri.Text.Replace("lastfm://", "lfm://"));

            if (AutoClose.Checked)
            {
                _timer.Interval = 3000;
                _timer.Start();
            }

        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            StoreSettings();
            RefreshPlayers();
        }

        private void RefreshPlayers()
        {
            try
            {
                // get squeezecenter
                string squeezeCenter = RetrieveSqueezeCenter;

                SqueezeCenterUrl.Text = squeezeCenter;
                _slim = new Slim(squeezeCenter);
                _players = _slim.RetrievePlayers();

                PlayersCombo.Items.Clear();
                for (int i = 0; i < _players.Length; i++)
                {
                    PlayersCombo.Items.Add(_slim.RetrievePlayerName(i));
                }
                                
                if (RetrievePlayerIndex <= _players.Length)
                    PlayersCombo.SelectedIndex = RetrievePlayerIndex;
                else
                    PlayersCombo.SelectedIndex = 0;
            }
            catch (SocketException se)
            {
                WrongSettings();
            }
        }

        private void StoreSettings()
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(_regKey);
            key.SetValue("SqueezeCenter", SqueezeCenterUrl.Text);
            key.SetValue("PlayerIndex", PlayersCombo.SelectedIndex);
        }

        private string RetrieveSqueezeCenter
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(_regKey);
                return (string)key.GetValue("SqueezeCenter", "Enter your SqueezeServer name here");
            }
        }

        private int RetrievePlayerIndex
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(_regKey);
                int index = (int)key.GetValue("PlayerIndex", 0);
                if (index < 0)
                    index = 0;
                return index;
            }
        }
        
        private void WrongSettings()
        {
            MessageBox.Show("Please check the SqueezeBox Server name. Just use the bare name or network address, i.e. 'MusicServer' or '192.168.0.10'. Good luck!",
                "SqueezeBox Server unreachable", MessageBoxButtons.OK);
        }

        private void SqueezeCenterUrl_TextChanged(object sender, EventArgs e)
        {
            StoreSettings();
            RefreshPlayers();
        }

        private void PlayersCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            StoreSettings();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog(this);
        }
    }
}
